import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, Alert, Divider, Icon, Badge, Tabs, Row, Col } from 'antd';
import '@/assets/css/settings';
import * as ProductionOrderService from '../../../axios/ProductionOrder'
import * as MaterialReceivingService from '../../../axios/CommissioningManagement'
import * as APIServiceYQ from '../../../axios/api_yq'
import * as APIService from '../../../axios/api'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareString } from '../../../components/TableCustomize'
import { withPermission } from '../../../components/withpermission';
import ProvideComponent from './ProvideComponent';
import SearchForm from './SearchForm';
import { withRouter } from 'react-router';
const CreateButton = withPermission(Button, 'create')
const { TabPane } = Tabs

class MaterialReceiving extends Component {
  state = {
    dataSource: [],
    advanced: false,
    departmentList: [],
    searchItem: {
      department: localStorage.getItem('workShop')
    },
    formData: {},
    pageSize: 10,
    pageNum: 1,
    total: 0,
    columns: [
      {
        title: '序号',
        dataIndex: 'dataIndex',
        width: 100,
        render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
      },
      {
        title: '领料单号',
        dataIndex: 'batchNo1',
        width: 100,
        sorter: (a, b) => compareString(a.batchNo1, b.batchNo1)
      },
      {
        title: '批号',
        dataIndex: 'batchNo',
        width: 100,
        sorter: (a, b) => compareString(a.batchNo, b.batchNo)
      },

      {
        title: '机型',
        width: 100,
        dataIndex: 'model',
        sorter: (a, b) => compareString(a.model, b.model),
        // editable: true
      },
      {
        title: '领料车间',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'department1',
        sorter: (a, b) => compareString(a.department1, b.department1)
      },
      {
        title: '领料班组',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'department',
        sorter: (a, b) => compareString(a.department, b.department)
      },
      {
        title: '班组长',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'assembleProcess',
        sorter: (a, b) => compareString(a.assembleProcess, b.assembleProcess)
      },
      {
        title: '领料项',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'testMachineProcess',
        sorter: (a, b) => compareString(a.testMachineProcess, b.testMachineProcess)
      },
      {
        title: '申请时间',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'qualityCheckProcess',
        sorter: (a, b) => compareDate(a.qualityCheckProcess, b.qualityCheckProcess)
      },
      {
        title: '装配开始时间',
        width: 150,
        dataIndex: 'isStates',
        sorter: (a, b) => compareDate(a.isStates, b.isStates),
      },
      {
        title: '需求时间',
        width: 150,
        dataIndex: 'firstDeliveryTime',
        sorter: (a, b) => compareDate(a.firstDeliveryTime, b.firstDeliveryTime)
      },
      {
        title: '操作',
        width: 200,
        dataIndex: 'opts',
        render: (text, record) => <>
          {/* <a onClick={() => this.create(1, record)}>接收</a> */}
          <a onClick={() => 'a'}>确认</a>
          {/* <a onClick={() => 'a'}>发放</a> */}
          <Divider type='vertical' />
          <a onClick={() => 'a'}>打印</a>
          <Divider type='vertical' />
          <a onClick={() => this.openDetails(record)}>详情</a>
          <Divider type='vertical' />
          <a onClick={() => this.openMaterial(1, record)}>提欠料</a>
        </>
      }
    ],
    childColumns: [
      {
        title: '序号',
        dataIndex: 'ids',
        width: 100,
        render: (text, record, index) => <span>{index + 1}</span>
      },
      {
        title: '发料仓库编码',
        width: 100,
        dataIndex: 'procedureCode',
        sorter: (a, b) => compareString(a.procedureCode, b.procedureCode),
        editable: true
      },

      {
        title: '仓库发料批次',
        width: 100,
        dataIndex: 'procedureName',
        sorter: (a, b) => compareString(a.procedureName, b.procedureName),
        editable: true
      },
      {
        title: '发料项',
        width: 100,
        dataIndex: 'assembleGroup',
        sorter: (a, b) => compareString(a.assembleGroup, b.assembleGroup),
        editable: true
      },
      {
        title: '发料时间',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'groupName',
        sorter: (a, b) => compareDate(a.groupName, b.groupName)
      },
      {
        title: '创建人',
        width: 100,
        dataIndex: 'groupUserName',
        sorter: (a, b) => compareString(a.groupUserName, b.groupUserName)
      },
      {
        title: '发料状态',
        width: 100,
        dataIndex: 'getMaterialProcess',
        sorter: (a, b) => compareString(a.getMaterialProcess, b.getMaterialProcess),
        render: (text) => {
          let a = this.state.workStatusList.find(item => item.id == text)
          return a.id == '0' ? <Badge status="default" text={<span style={{ color: '#d9d9d9' }}>{a.value}</span>} />
            : a.id == '2' ? <Badge status="warning" text={<span style={{ color: '#ffc440' }}>{a.value}</span>} />
              : a.id == '1' ? <Badge status="success" text={<span style={{ color: '#1e8e3e' }}>{a.value}</span>} />
                : a.id === '3' ? <Badge color='#1890ff' text={<span style={{ color: '#1890ff' }}>{a.value}</span>} /> : a.value
        }
      },
      {
        title: '接收时间',
        width: 100,
        dataIndex: 'distributeMaterialProcess',
        sorter: (a, b) => compareDate(a.distributeMaterialProcess, b.distributeMaterialProcess)
      },
      {
        title: '接收人',
        width: 100,
        dataIndex: 'receiveMaterialProcess',
        sorter: (a, b) => compareString(a.receiveMaterialProcess, b.receiveMaterialProcess)
      },
    ],
    selectedRows: [],
    selectedRowKeys: [],
    chooseRecord: [],
    modalTitle: '',

    activeKey: '1',
    row: [],
    visible: false,
  };
  componentDidMount() {
    this.getList()
    if (this.props.location.data) {
      this.setState({ searchItem: this.props.location.data }, this.fetch)
    } else {
      this.fetch()
    }
  }
  // 派工班组查询
  getList = () => {
    ProductionOrderService.findGroupAll().then(res => {
      const departmentList = res.data.data
      this.setState({ departmentList });
    })
  }
  //初始化加载数据
  fetch = (pageNum = 1, pageSize = 100) => {
    this.setState({ loading: true })
    const { searchItem } = this.state
    searchItem.pageNum = pageNum
    searchItem.pageSize = pageSize
    // let str = ''
    // for (var key in searchItem) {
    //   if (searchItem[key] || searchItem[key] === 0) {
    //     str += `&${key}=${searchItem[key]}`
    //   }
    // }

    MaterialReceivingService.findMachineAssignAll(searchItem).then(res => {
      this.setState({ loading: false })
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }

  handleCancel = e => {
    this.setState({
      selectedRowKeys: [],
      selectedRows: [],
      visible: false,
    });
    this.fetch();
  };


  handleSearch = value => {
    console.log(value)
    if (value.assembleStartDate && value.assembleStartDate.length === 2) {
      value.firstOutputDateMin = value.assembleStartDate[0].format('YYYY-MM-DD 00:00:00')
      value.firstOutputDateMax = value.assembleStartDate[1].format('YYYY-MM-DD 23:59:59')
      delete (value.assembleStartDate)
    }
    if (value.firstDeliveryDate && value.firstDeliveryDate.length === 2) {
      value.firstDeliveryDateMin = value.firstDeliveryDate[0].format('YYYY-MM-DD 00:00:00')
      value.firstDeliveryDateMax = value.firstDeliveryDate[1].format('YYYY-MM-DD 23:59:59')
      delete (value.firstDeliveryDate)
    }
    this.setState({ searchItem: value }, this.fetch);
  };

  onHandleAdvanced = () => {
    this.setState({ advanced: !this.state.advanced })
  }
  loadData = (value, dataSource) => {
    console.log(value, dataSource)
  }
  // 选择某一行数据
  chooseRow = record => {
    let flag = true;
    let index = 0;
    this.state.selectedRowKeys.forEach((row, i) => {
      if (row === record.batchNo) {
        flag = false;
        index = i;
      }
    })
    const selectedRowKeys = this.state.selectedRowKeys;
    const selectedRows = this.state.selectedRows;
    if (flag) {
      selectedRowKeys.push(record.batchNo);
      selectedRows.push(record);
    } else {
      selectedRowKeys.splice(index, 1);
      selectedRows.splice(index, 1);
    }
    this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
  };
  // 选择某一行数据
  chooseRowChild = record => {
    const { detailList } = this.state
    let flag = true;
    let index = 0;
    this.state.selectedRowKeysChild.forEach((row, i) => {
      if (row === record.workUniqueType) {
        flag = false;
        index = i;
      }
    })
    const selectedRowKeys = this.state.selectedRowKeysChild;
    const selectedRows = this.state.selectedRowsChild;
    if (flag) {
      selectedRowKeys.push(record.workUniqueType);
      selectedRows.push(record);
    } else {
      selectedRowKeys.splice(index, 1);
      selectedRows.splice(index, 1);
    }
    this.setState({ selectedRowKeysChild: selectedRowKeys, selectedRowsChild: selectedRows });
  };
  // 展开方法
  onExpand = (expanded, record) => {
    const that = this;
    if (expanded) {
      // console.log(record, 'record------')
      // console.log(this.state.searchItem, 'searchItem------')
      let obj = {
        ...this.state.searchItem,
        ...record,
        pageSize: 1000,
        pageNum: 1
      }
      // console.log(obj, 'obj------');
      // const searchTerm = { ...that.state.searchTerm };
      // searchTerm.productionNum = record.productionNum;
      // ProductionOrderService.findPlanDetailsAll(obj).then(res => {
      //   // console.log(res, 'findPlanDetailsAll')
      //   this.setState({
      //     detailList: res.data.data,
      //     row: [record.batchNo],
      //     expandedData: record
      //   })
      // })
    } else {
      this.setState({
        row: []
      })
    }
  }

  downloadFather = () => {
    const { selectedRows } = this.state;
    if (selectedRows.length) {
      this.setState({ downloadLoading: true });
      MaterialReceivingService.exportTestMachineManageExcel({ list: selectedRows }).then(res => {
        //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
        let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
        // 创建A标签
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        // 设置的下载文件文件名
        const fileName = decodeURI('试机管理');
        // 触发点击方法
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
        this.setState({ downloadLoading: false })
      })
    } else {
      Modal.confirm({
        title: '默认导出数据较多，需要较长时间，确认全部导出吗？',
        onOk: async () => {
          await this.fetchAll();
          const { dataSourceAll } = this.state;
          await MaterialReceivingService.exportTestMachineManageExcel({ list: dataSourceAll }).then(res => {
            //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
            let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
            // 创建A标签
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            // 设置的下载文件文件名
            const fileName = decodeURI('试机管理');
            // 触发点击方法
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()
            this.setState({ downloadLoading: false })
          })
        },
        onCancel() { }
      })
    }
  }
  fetchAll = async () => {
    const { searchItem, total } = this.state
    searchItem.pageNum = 1
    searchItem.pageSize = total
    // let str = ''
    // for (var key in searchItem) {
    //   if (searchItem[key] || searchItem[key] === 0) {
    //     str += `&${key}=${searchItem[key]}`
    //   }
    // }
    await MaterialReceivingService.findMachineAssignAll(searchItem).then(res => {
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      const dataSourceAll = res.data.data.data
      const selectedRowKeys = dataSourceAll.map(item => item.batchNo);
      this.setState({ dataSourceAll, selectedRowKeys, selectedRows: dataSourceAll })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }
  // 打开详情页
  openDetails = (record) => {
    const { searchItem } = this.state;
    const data = {}
    data.batchNo = [record.batchNo]
    data.model = record.model
    localStorage.setItem('MaterialReceiving_searchItem', JSON.stringify(searchItem));
    localStorage.setItem('MaterialReceiving_detailsList', JSON.stringify(data));
    this.props.history.push({ pathname: "/MaterialReceiving_Details", data: { record: data, searchItem } })
  }
  // 点击提欠料按钮   0 提交选择的欠料   1 提交一条
  openMaterial = (type, record = {}) => {
    const { selectedRows } = this.state
    let chooseRecord = []
    if (type === 1) {
      chooseRecord.push(record)
    } else {
      if (!selectedRows || !selectedRows.length) {
        openModalMessage('warning', '请选择要提交的欠料单！');
        return;
      }
      chooseRecord = selectedRows
    }
    this.setState({
      visible: true,
      modalTitle: '物料发放结果',
      chooseRecord,
    });
  }
  // 发布欠料
  submit = (data) => {
    console.log(data, 'submit');
    openModalMessage('warning', '暂无此功能！');
  }
  // 提交欠料   0 提交全部欠料   1 提交一条
  submitMaterial = (type, data = {}) => {
    console.log(data, 'submitMaterial');
    const { chooseRecord } = this.state
    let params = []
    if (type === 1) {
      params.push(data)
    } else {
      params = chooseRecord
    }

  }
  print = (data) => {
    console.log(data, 'print');
    openModalMessage('warning', '暂无此功能！');
  }
  onChangeTabs = activeKey => {
    this.setState({ activeKey });
  };

  resetForm = () => {
    this.formSearch && this.formSearch.resetFields();
    this.setState({
      searchItem: {
        department: localStorage.getItem('workShop')
      }
    }, this.fetch);
  }
  render() {
    const { departmentList, modalTitle, btnLoading, chooseRecord, loading, dataSource, formData, advanced, columns, pageNum, pageSize, total, selectedRowKeys, downloadLoading, searchItem, visible } = this.state;
    const rowSelection = {
      type: 'checkbox',
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        })
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        const keys = [... this.state.selectedRowKeys];
        const rows = [... this.state.selectedRows];
        if (selected) {
          changeRows.forEach(row => {
            if (isInvalidObject(keys.find(key => key === row.batchNo))) {
              keys.push(row.batchNo);
              rows.push(row);
            }
          })
        } else {
          changeRows.forEach(row => {
            keys.splice(keys.indexOf(row.batchNo), 1);
            rows.splice(rows.indexOf(row), 1);
          })
        }
        this.setState({ selectedRows: rows, selectedRowKeys: keys })
      }
    }
    const spanStyle = { color: '#fd1818', margin: '0 3px' }
    const expandedRowRender = () => {
      const { childColumns } = this.state;
      return <TableCustomize
        onRow={(record, rowKey) => ({
          onClick: this.chooseRowChild.bind(this, record, rowKey)
        })}
        allowDrafting={true}
        dataSource={this.state.detailList}
        columns={childColumns}
        pagination={false}
        scroll={{ y: 300 }}
        rowKey={record => record.workUniqueType}
      />;
    };
    return (
      <div>
        <BasicLayoutSearch>
          <SearchForm onSearch={this.handleSearch}
            onClick={this.onHandleAdvanced}
            advanced={advanced}
            searchItem={searchItem}
            departmentList={departmentList}
            resetForm={this.resetForm}
            ref={node => (this.formSearch = node)}
          />
        </BasicLayoutSearch>
        <Tabs tabBarExtraContent={(
          <div className='mydiv'>
            {[
              <Button key={0} type="primary" onClick={() => this.openMaterial()} icon="sort-ascending">批量提欠料</Button>,
              <Button key={1} type="primary" onClick={() => this.print()} icon="print">打印</Button>,
              <Button type="primary" key={2} onClick={this.downloadFather} icon="download" loading={downloadLoading}>导出</Button>,
            ]}
          </div>
        )}
          hideAdd
          className="layout-model"
          onChange={this.onChangeTabs}
          activeKey={this.state.activeKey}
          type="card">
          <TabPane tab={'物料接收-总计'} key="1">
            <Alert message={<div>已选择<span style={{ color: '#fd1818', margin: '0 3px' }}>{selectedRowKeys.length}</span>项</div>} type="info" showIcon style={{ marginBottom: 15 }} />
            <TableCustomize
              columns={columns}
              rowKey={(record) => record.batchNo}
              dataSource={dataSource}
              pagination={false}
              loading={loading}
              allowDrafting={true}
              allowRowEdit
              allowEditable={this.loadData}
              rowSelection={rowSelection}
              onRow={(record, rowKey) => ({
                onClick: this.chooseRow.bind(this, record, rowKey)
              })}
              expandedRowKeys={this.state.row}
              expandedRowRender={expandedRowRender}
              onExpand={(expanded, record) => this.onExpand(expanded, record)}
            />

            <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
          </TabPane>
          <TabPane tab={'物料接收-实收'} key="2">
            物料接收-实收
            {/* <Details
              dataSource={dataSource}
              searchItem={searchItem}
            /> */}
          </TabPane>
          <TabPane tab={'统计分析'} key="3">
            统计分析
            {/* <Details
              dataSource={dataSource}
              searchItem={searchItem}
            /> */}
          </TabPane>
        </Tabs>

        {/* 发放 */}
        <Modal
          visible={visible}
          destroyOnClose
          title={modalTitle}
          onCancel={() => this.handleCancel()}
          footer={
            <div>
              <Button type='default' onClick={this.handleCancel}>取消</Button>
              <Button type='primary' onClick={this.submitMaterial}>全部提交欠料</Button>
              <Button type='primary' onClick={this.print}>打印</Button>
            </div>
          }
          width={'70%'}
          maskClosable={false}
          confirmLoading={btnLoading}
        >
          <ProvideComponent
            chooseRecord={chooseRecord}
            onHandelSubmit={this.submitMaterial}    // 提交欠料
            onHandelPrint={this.print}    // 打印
            onHandelClick={this.submit}   // 发布欠料
          />

        </Modal>

      </div>
    );
  }
}
export default Form.create()(withRouter(MaterialReceiving));